package com.juku2024.juku.fragment

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.juku2024.juku.*
import com.juku2024.juku.adapter.HomeTabFragmentAdapter
import com.juku2024.juku.base.BaseFragment
import com.juku2024.juku.callback.OnNoDoubleClickListener
import com.juku2024.juku.db.entity.HomeModel
import com.juku2024.juku.viewmodel.MainViewModel
import com.google.android.material.tabs.TabLayoutMediator
import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.model.Genre
import com.juku2024.juku.model.Notice
import com.juku2024.juku.model.UpdateModel
import com.juku2024.juku.tools.AnalysisConstants
import com.juku2024.juku.tools.AnalysisUtils
import com.juku2024.juku.tools.Constants
import com.juku2024.juku.tools.SPUtil
import com.juku2024.juku.widget.LoadingView

class HomeFragment : BaseFragment() {

    private lateinit var viewPager: ViewPager2
    private lateinit var homeTabTop: View
    private lateinit var favorite: View
    private lateinit var history: View
    private lateinit var download: View
    private lateinit var loadingView: LoadingView
    private lateinit var tabLayout: TabLayout

    private var genreList: ArrayList<Genre>? = null
    private val viewModel by lazy { getViewModel(requireActivity().viewModelStore, MainViewModel::class.java) }

    override fun layoutView(inflater: LayoutInflater, container: ViewGroup?): View {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun initView(rootView: View) {
        super.initView(rootView)
        viewPager = rootView.findViewById(R.id.viewPager_home)
        homeTabTop = rootView.findViewById(R.id.homeTabTop)
        favorite = rootView.findViewById(R.id.favorite)
        history = rootView.findViewById(R.id.history)
        download = rootView.findViewById(R.id.download)
        loadingView = rootView.findViewById(R.id.loadingView_home)
        tabLayout = rootView.findViewById(R.id.tabLayout_home)


        viewPager.orientation = ViewPager2.ORIENTATION_HORIZONTAL
        viewPager.isUserInputEnabled = true
    }

    override fun bindEvent() {
        super.bindEvent()
        homeTabTop.setOnClickListener {
            val intent = Intent(requireContext(), SearchActivity::class.java)
            startActivity(intent)
        }
        favorite.setOnClickListener(object : OnNoDoubleClickListener {
            override fun onNoDoubleClick(v: View?) {
                super.onNoDoubleClick(v)
                val intent = Intent(requireContext(), FavoriteActivity::class.java)
                startActivity(intent)
            }
        })
        history.setOnClickListener(object : OnNoDoubleClickListener {
            override fun onNoDoubleClick(v: View?) {
                super.onNoDoubleClick(v)
                val intent = Intent(requireContext(), HistoryActivity::class.java)
                startActivity(intent)
            }
        })

        download.setOnClickListener(object : OnNoDoubleClickListener {
            override fun onNoDoubleClick(v: View?) {
                super.onNoDoubleClick(v)
                if (BaseApplication.isLimited) return
                val intent = Intent(requireContext(), DownloadDetailActivity::class.java)
                startActivity(intent)
            }
        })
    }

    override fun init(savedInstanceState: Bundle?) {
        // 申请推送消息权限
        requestFirebaseNotificationPermission()
        super.init(savedInstanceState)
        if (genreList.isNullOrEmpty()) {
            loadingView.showLoading()
            doHttpMainHome()
        } else {
            initTab()
        }
    }


    private fun doHttpMainHome() {
        loadingView.showLoading()
        viewModel.doHttpHome({ news: Int, updateModel: UpdateModel?, notice: Notice?, homeModel: HomeModel? ->
            if (isFragmentNotActive()) return@doHttpHome
            loadingView.hideLoading()
            val activity = requireActivity() as MainActivity
            // 优先处理升级，并且升级和通知不能同时存在
            if (updateModel != null) {
                val typeStr = if (updateModel.type == 0) "弹窗" else "页面"
                AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE_V2, AnalysisConstants.KEY_SHOW_DIALOG, "首页接口 -> $typeStr")
                if (updateModel.type == 0) {
                    activity.showUpgradeDialog(updateModel)
                } else {
                    val intent = Intent(requireContext(), UpgradeActivity::class.java)
                    intent.putExtra(Constants.INTENT_KEY_UPDATE, updateModel)
                    startActivity(intent)
                    if (updateModel.foreceUpdate) {
                        requireActivity().finish()
                    }
                }
            } else { // 没有升级的情况下，才能加载通知
                activity.showNotifyDialog(notice)
            }
            // 处理系统反馈
            activity.initNotify(news)
            // 最后处理首页nav接口
            if (homeModel == null) {
                showErrorRetryView(null)
                return@doHttpHome
            }
            genreList = homeModel.genres
            if (genreList.isNullOrEmpty()) { // 未知出现异常，建议让用户退出重进
                showErrorDialog("未知错误，建议您退出后重启App", "退出", {
                    requireActivity().finish()
                })
                return@doHttpHome
            }
            initTab()
        }, {
            if (isFragmentNotActive()) return@doHttpHome
            loadingView.hideLoading()
            showErrorRetryView(it)
        })
    }

    private fun initTab() {
        val fragments = ArrayList<BaseFragment>()
        genreList?.forEach {
            fragments.add(HomeTabFragment.init(it.id))
        }
        val tabAdapter = HomeTabFragmentAdapter(this, fragments)
        viewPager.adapter = tabAdapter
        TabLayoutMediator(tabLayout, viewPager, true) { tab, position ->
            tab.text = genreList?.get(position)?.name
        }.attach()



    }


    private fun showErrorRetryView(msg: String?) {
        val it = msg ?: "当前分类获取失败，请重试!"
        loadingView.showErrorStatus(
            it,
            getString(R.string.retry)
        ) {
            loadingView.showLoading()
            loadingView.postDelayed({
                if (isFragmentNotActive()) return@postDelayed
                doHttpMainHome()
            }, 1000)
        }
    }

    private fun requestFirebaseNotificationPermission() {
        if (BaseApplication.isLimited || SPUtil.instance.isRefuseNotification) return

        // sdk 33才有要求请求该权限
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU && ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission
                .POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
            return
        }

        val launcherPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
            if (it) {
                //同意

            } else {
                //拒绝，解释原因
                showErrorDialog(
                    "我们只会给您发送新剧更新的消息通知，我们不会发送任何其他与剧无关的消息通知。您若关闭，将无法收到新剧更新的消息提醒！",
                    "授权",
                    {
                        ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1001)
                    },
                    "拒绝",
                    {
                        SPUtil.instance.isRefuseNotification = true
                    })
            }
        }
        launcherPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
    }

}